package com.chapter.sample.juc.tl;

import java.lang.ref.*;
import java.util.concurrent.TimeUnit;

class MyObject {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("---------------gc，finalize() invoked");
    }
}

public class ReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue<MyObject> referenceQueue = new ReferenceQueue<>();
        PhantomReference<MyObject> phantomReference = new PhantomReference<MyObject>(new MyObject(), referenceQueue);
        System.out.println("gc before内存够用：" + phantomReference.get());
        System.gc();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("gc after内存不够：" + phantomReference.get());
        Reference<? extends MyObject> poll = referenceQueue.poll();
        TimeUnit.SECONDS.sleep(1);
        if (poll != null) {
            System.out.println("!12222222231213");
        }

    }

    private static void WeakReference() throws InterruptedException {
        WeakReference<MyObject> weakReference = new WeakReference<>(new MyObject());
        System.out.println("gc before内存够用：" + weakReference.get());
        System.gc();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("gc after内存不够：" + weakReference.get());
    }

    private static void softReference() {
        SoftReference<MyObject> softReference = new SoftReference<>(new MyObject());
        System.out.println("gc before内存够用：" + softReference);
        System.gc();
        System.out.println("gc after内存不够：" + softReference);
    }

    private static void strongReference() {
        MyObject myObject = new MyObject();
        System.out.println("gc before：" + myObject);
        myObject = null;
        System.gc();
        System.out.println("gc after：" + myObject);
    }
}
